/**
 *
 */
package co.fitstart.admin.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zaxxer.hikari.HikariPoolMXBean;

/**
 * @author lute
 */
public class HikariPoolLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(HikariPoolLoggingFilter.class);

    private HikariPoolMXBean poolProxy;

    /* (non-Javadoc)
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        poolProxy = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean(HikariPoolMXBean.class);
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.trace("#doFilter - Get [{}] idle connections.", poolProxy.getIdleConnections());
        logger.trace("#doFilter - Get [{}] active connections.", poolProxy.getActiveConnections());
        logger.trace("#doFilter - Get [{}] total connections.", poolProxy.getTotalConnections());
        logger.trace("#doFilter - Get [{}] threads awaiting connections.", poolProxy.getThreadsAwaitingConnection());
        chain.doFilter(request, response);
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {

    }

}

